/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.marcelo.agro.productos.gui;

import java.awt.Component;
import java.awt.Dialog;
import java.awt.event.*;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import org.marcelo.agro.entidades.*;
import org.marcelo.agro.productos.model.ProductosModel;

/**
 *
 * @author marcelo
 */
public class AgregarProductos extends javax.swing.JPanel implements ActionListener{

    /**
     * Creates new form AgregarProductos
     */
    private ProductosModel model;
    public static final String PROPIEDAD_SALIR = "salir";
    private String TITULO_VENTANA = "";
    //Como este panel esta embedido en un dialogo lo que are es guardar una referencia
    // a este dialogo, y lo cerrare desde aca
    private Dialog parent;
    
    public void setParent(Dialog parent){
        this.parent = parent;
        TITULO_VENTANA = parent.getTitle();
    }
    public AgregarProductos(Productos productos) {
        initComponents();
        model = new ProductosModel(productos);
        addListeners();
        initComboBoxModel();
        loadFromPom();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        controles = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        nombre = new javax.swing.JTextField();
        cbFabricante = new javax.swing.JComboBox();
        cbRegistrante = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        precio = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        toxicidad = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        cbPaisOrigen = new javax.swing.JComboBox();
        cbTipoPresentacion = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        btnGuardar = new javax.swing.JButton();
        btnAgregarMas = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        lblError = new javax.swing.JLabel();

        controles.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.controles.border.title"))); // NOI18N

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel1.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.jLabel1.text")); // NOI18N

        nombre.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.nombre.text")); // NOI18N

        cbFabricante.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        cbRegistrante.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel3.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.jLabel3.text")); // NOI18N

        precio.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.precio.text")); // NOI18N

        jLabel4.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.jLabel4.text")); // NOI18N

        toxicidad.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.toxicidad.text")); // NOI18N

        jLabel5.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.jLabel5.text")); // NOI18N

        jPanel2.setLayout(new java.awt.GridBagLayout());

        cbPaisOrigen.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        cbTipoPresentacion.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel6.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.jLabel6.text")); // NOI18N

        jLabel7.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.jLabel7.text")); // NOI18N

        jLabel2.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.jLabel2.text")); // NOI18N

        javax.swing.GroupLayout controlesLayout = new javax.swing.GroupLayout(controles);
        controles.setLayout(controlesLayout);
        controlesLayout.setHorizontalGroup(
            controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(controlesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(controlesLayout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(18, 18, 18)
                        .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbPaisOrigen, javax.swing.GroupLayout.Alignment.TRAILING, 0, 212, Short.MAX_VALUE)
                            .addComponent(cbTipoPresentacion, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(precio, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(nombre, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(controlesLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(52, 52, 52)
                        .addComponent(cbFabricante, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(controlesLayout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(47, 47, 47)
                        .addComponent(cbRegistrante, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(controlesLayout.createSequentialGroup()
                        .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel6)
                            .addComponent(jLabel1)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(controlesLayout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(58, 58, 58)
                        .addComponent(toxicidad)))
                .addContainerGap())
        );
        controlesLayout.setVerticalGroup(
            controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(controlesLayout.createSequentialGroup()
                .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(controlesLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(controlesLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(precio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))))
                .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(controlesLayout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addComponent(jLabel3))
                    .addGroup(controlesLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbFabricante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(cbRegistrante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(toxicidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(cbPaisOrigen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(controlesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(cbTipoPresentacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jToolBar1.setRollover(true);

        btnGuardar.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.btnGuardar.text")); // NOI18N
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnGuardar);

        btnAgregarMas.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.btnAgregarMas.text")); // NOI18N
        btnAgregarMas.setFocusable(false);
        btnAgregarMas.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnAgregarMas.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAgregarMas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarMasActionPerformed(evt);
            }
        });
        jToolBar1.add(btnAgregarMas);

        btnCancelar.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.btnCancelar.text")); // NOI18N
        btnCancelar.setFocusable(false);
        btnCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnCancelar);

        lblError.setText(org.openide.util.NbBundle.getMessage(AgregarProductos.class, "AgregarProductos.lblError.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(controles, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblError, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(controles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(lblError)
                .addContainerGap(38, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        exit();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        model.guardar();
        exit();
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnAgregarMasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarMasActionPerformed
        // TODO add your handling code here:
        model.agregarMas();
        loadFromPom();
    }//GEN-LAST:event_btnAgregarMasActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregarMas;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cbFabricante;
    private javax.swing.JComboBox cbPaisOrigen;
    private javax.swing.JComboBox cbRegistrante;
    private javax.swing.JComboBox cbTipoPresentacion;
    private javax.swing.JPanel controles;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblError;
    private javax.swing.JTextField nombre;
    private javax.swing.JTextField precio;
    private javax.swing.JTextField toxicidad;
    // End of variables declaration//GEN-END:variables
    /**
     * MEtodos agregados por marcelo
     */
    Integer SELECCIONADO = ItemEvent.SELECTED;
    ItemListener il = new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == SELECCIONADO) {
                //sync
                syncWithPom();
            }
        }
    };
    FocusListener fl = new FocusAdapter() {

        @Override
        public void focusLost(FocusEvent e) {
            super.focusLost(e);
            //sync
            syncWithPom();
        }
    
    };
    
    private void addListeners() {
        Component[] components = controles.getComponents();
        for (Component c : components){
            if (c instanceof JComboBox) {
                ((JComboBox)c).addItemListener(il);
            }
            if (c instanceof JTextField ) {
                ((JTextField) c).addFocusListener(fl);
            }
        }
    }
    
    private Boolean isLoading = false;
    
    private Boolean notLoading(){
        return !isLoading;
    }
    
    private void syncWithPom(){
        if (notLoading()){
            saveToPom();
            loadFromPom();
        }
    }
    
    private void loadFromPom(){
        //Botones
        isLoading = true;
        btnGuardar.setEnabled(model.isEnableGuardar());
        btnAgregarMas.setEnabled(model.isEnableAgregarMas());
        
        //Valores
        cbFabricante.setSelectedItem(model.getFabricante());
        nombre.setText(model.getNombre());
        cbPaisOrigen.setSelectedItem(model.getPaisOrigen());
        precio.setText(model.getPrecio().toString());
        cbRegistrante.setSelectedItem(model.getRegistrante());
        cbTipoPresentacion.setSelectedItem(model.getTipoPresentacion());
        toxicidad.setText(model.getToxicidad());
        
        lblError.setText(model.getMensajeError());
        lblError.setVisible(model.haveError());
        //manipular el texto del titulo de la ventana
        if (model.changed())
            if (parent != null)
                parent.setTitle(TITULO_VENTANA + " *modificado");
        else 
            if (parent != null) 
                parent.setTitle(TITULO_VENTANA);
        isLoading = false;
    }
    
    private void saveToPom(){
        model.setFabricante(cbFabricante.getSelectedItem());
        model.setNombre(nombre.getText());
        model.setPaisOrigen(cbPaisOrigen.getSelectedItem());
        model.setPrecio(precio.getText());
        model.setRegistrante(cbRegistrante.getSelectedItem());
        model.setTipoPresentacion(cbTipoPresentacion.getSelectedItem());
        model.setToxicidad(toxicidad.getText());    
    }
    
    private void initComboBoxModel() {
        
        Fabricante[] itemsFabricantes = model.getFabricantes().toArray(new Fabricante[0]);
        Registrante[] itemsRegistrante = model.getRegistrantes().toArray(new Registrante[0]);
        Pais[] itemsPais = model.getPaises().toArray(new Pais[0]);
        TipoPresentacion[] itemsTipoPresentacions = model.getTipoPresentaciones().toArray(new TipoPresentacion[0]);
        
        DefaultComboBoxModel<Fabricante> cbModelFabricante = new DefaultComboBoxModel<Fabricante>(itemsFabricantes);
        DefaultComboBoxModel<Pais> cbModelPaisOrigen = new DefaultComboBoxModel<Pais>(itemsPais);
        DefaultComboBoxModel<Registrante> cbModelRegistrante = new DefaultComboBoxModel<Registrante>(itemsRegistrante);
        DefaultComboBoxModel<TipoPresentacion> cbModelTipoPresentacion = new DefaultComboBoxModel<TipoPresentacion>(itemsTipoPresentacions);
        
        cbFabricante.setModel(cbModelFabricante);
        cbPaisOrigen.setModel(cbModelPaisOrigen);
        cbRegistrante.setModel(cbModelRegistrante);
        cbTipoPresentacion.setModel(cbModelTipoPresentacion);
    }
    
    private void exit(){
        if (model.changed()){
            model.refresh();
        }
        firePropertyChange(PROPIEDAD_SALIR, 0, 1);
        removerListeners();
        parent.dispose();
    }

    private void removerListeners() {
        Component[] components = controles.getComponents();
        for (Component c : components){
            if (c instanceof JComboBox) {
                ((JComboBox)c).removeItemListener(il);
            }
            if (c instanceof JTextField ) {
                ((JTextField) c).removeFocusListener(fl);
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals("Close")) {
            //Mostrar un mensaje
        }

    }
}
